//
// Created by Senhai Xu on 2025/3/19.
//
#include <iostream>
#include <thread>
#include <mutex>
#include <memory>
using namespace std;
timed_mutex mtx;
void func(int *count)
{
    for (int i = 0; i < 5; i++)
    {
        // lock_guard<mutex> lock(mtx);
        unique_lock<timed_mutex> lock(mtx, std::defer_lock);
        if(lock.try_lock_for(chrono::milliseconds(1))){
            this_thread::sleep_for(chrono::milliseconds(2));
            (*count)++;
        }
        
    }

};
int main()
{
    // 线程函数中的数据未定义错误 传递指针或引用指向局部变量的问题
    // int x = 1;
    // std::thread t(func, &x); // 传递指向局部变量的指针
    shared_ptr<int> count = make_shared<int>(0);
    std::thread t1(func, count.get());
    std::thread t2(func, count.get());
    t1.join();
    t2.join();
    cout << *count << endl;
    return 0;
}
